<template>
    <div>
        <el-breadcrumb separator-class = "el-icon-arrow-right">
            <el-breadcrumb-item :to = "{ path: '/home', name: '首页' }"
            >首页
            </el-breadcrumb-item
            >
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                    :closable = "false"
                    show-icon
                    title = "注意：只允许为三级分类设置相应参数"
                    type = "warning"
            ></el-alert>

            <!-- 选中商品分类区域 -->
            <el-row>
                <el-col :span = "24">
                    <span>选中商品分类：</span>
                    <!-- 级联选择框 -->
                    <el-cascader
                            :options = "cateList"
                            :props = "cateProps"
                            @change = "selectChanged"
                            expand-trigger = "hover"
                            v-model = "selectedCateKeys"
                    >
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页签区 -->
            <el-row>
                <el-col>
                    <el-tabs
                            @tab-click = "handleTabClick"
                            type = "border-card"
                            v-model = "activeName"
                    >
                        <el-tab-pane label = "动态参数" name = "many">
                            <el-button
                                    :disabled = "isBtnDisabled"
                                    @click = "addParamsDialogVisible = true"
                                    size = "mini"
                                    type = "primary"
                            >添加参数
                            </el-button
                            >
                            <!-- 动态参数表格 -->
                            <el-table
                                    :data = "manyTableData"
                                    border
                                    empty-text = "请选择分类"
                                    stripe
                            >
                                <!-- 展开行 -->
                                <el-table-column type = "expand">
                                    <template slot-scope = "scope">
                                        <!-- 循环渲染Tag标签-->
                                        <el-tag :key = "i" @close = "HandleClose(i,scope.row)" closable
                                                type = "info"
                                                v-for = "(item,i) in scope.row.attr_vals"
                                        >
                                            {{item}}
                                        </el-tag>
                                        <!--输入文本框-->
                                        <el-input
                                                @blur = "handleInputConfirm(scope.row)"
                                                @keyup.enter.native = "handleInputConfirm(scope.row)"
                                                class = "input-new-tag"
                                                ref = "saveTagInput"
                                                size = "small"
                                                v-if = "scope.row.inputVisible"
                                                v-model = "scope.row.inputValue"
                                        >
                                        </el-input>
                                        <el-button @click = "showInput(scope.row)" class = "button-new-tag" size = "small"
                                                   v-else>+ New Tag
                                        </el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column label = "#" type = "index"></el-table-column>
                                <el-table-column
                                        key = "attr_id"
                                        label = "参数名称"
                                        prop = "attr_name"
                                >
                                </el-table-column>
                                <el-table-column label = "操作">
                                    <template slot-scope = "scope">
                                        <el-button
                                                @click = "showEditDialog(scope.row.attr_id)"
                                                icon = "el-icon-edit"
                                                size = "mini"
                                                type = "success"
                                        >
                                            编辑
                                        </el-button
                                        >
                                        <el-button @click = "deleteParams(scope.row.attr_id)" icon = "el-icon-delete"
                                                   size = "mini"
                                                   type = "danger"
                                        >删除
                                        </el-button
                                        >
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label = "静态属性" name = "only">
                            <el-button
                                    :disabled = "isBtnDisabled"
                                    @click = "addParamsDialogVisible = true"
                                    size = "mini"
                                    type = "primary"
                            >添加属性
                            </el-button
                            >
                            <!-- 静态参数表格 -->
                            <el-table
                                    :data = "onlyTableData"
                                    border
                                    empty-text = "请选择分类"
                                    stripe
                            >
                                <!-- 展开行 -->
                                <el-table-column label = "  " type = "expand">
                                    <template slot-scope = "scope">
                                        <!-- 循环渲染Tag标签-->
                                        <el-tag :key = "i" @close = "HandleClose(i,scope.row)" closable
                                                type = "info"
                                                v-for = "(item,i) in scope.row.attr_vals"
                                        >
                                            {{item}}
                                        </el-tag>
                                        <!--输入文本框-->
                                        <el-input
                                                @blur = "handleInputConfirm(scope.row)"
                                                @keyup.enter.native = "handleInputConfirm(scope.row)"
                                                class = "input-new-tag"
                                                ref = "saveTagInput"
                                                size = "small"
                                                v-if = "scope.row.inputVisible"
                                                v-model = "scope.row.inputValue"
                                        >
                                        </el-input>
                                        <el-button @click = "showInput(scope.row)" class = "button-new-tag" size = "small"
                                                   v-else>+ New Tag
                                        </el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column label = "#" type = "index"></el-table-column>
                                <el-table-column
                                        key = "attr_id"
                                        label = "属性名称"
                                        prop = "attr_name"
                                >
                                </el-table-column>
                                <el-table-column label = "操作">
                                    <template slot-scope = "scope">
                                        <el-button
                                                @click = "showEditDialog(scope.row.attr_id)"
                                                icon = "el-icon-edit"
                                                size = "mini"
                                                type = "success"
                                        >
                                            编辑
                                        </el-button
                                        >
                                        <el-button @click = "deleteParams(scope.row.attr_id)" icon = "el-icon-delete"
                                                   size = "mini"
                                                   type = "danger"
                                        >删除
                                        </el-button
                                        >
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
            <!-- card body -->
        </el-card>
        <el-dialog
                :title = "'添加' + titleText"
                :visible.sync = "addParamsDialogVisible"
                @close = "addDialogClosed"
                width = "50%"
        >
            <!-- 添加参数对话框 -->
            <el-form
                    :model = "addParamsForm"
                    :rules = "addParamsFormRules"
                    label-width = "80px"
                    ref = "addParamsFormRef"
            >
                <el-form-item :label = "titleText" prop = "attr_name">
                    <el-input v-model = "addParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <span slot = "footer">
        <el-button @click = "addParamsDialogVisible = false">取 消</el-button>
        <el-button @click = "addParams" type = "primary">确 定</el-button>
      </span>
        </el-dialog>
        <el-dialog
                :title = "'修改' + titleText"
                :visible.sync = "editParamsDialogVisible"
                @close = "editDialogClosed"
                width = "50%"
        >
            <!-- 修改参数对话框 -->
            <el-form
                    :model = "editParamsForm"
                    :rules = "editParamsFormRules"
                    label-width = "80px"
                    ref = "editParamsFormRef"
            >
                <el-form-item :label = "titleText" prop = "attr_name">
                    <el-input v-model = "editParamsForm.attr_name"></el-input>
                </el-form-item>
            </el-form>

            <span slot = "footer">
        <el-button @click = "editParamsDialogVisible = false">取 消</el-button>
        <el-button @click = "editParams" type = "primary">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                cateList: [],
                selectedCateKeys: [],
                cateProps: {
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    disabled: 'cat_deleted',
                    children: 'children'
                },
                //被激活的页签名称
                activeName: 'many',
                // 静态参数的数据
                onlyTableData: [],
                // 动态参数的数据
                manyTableData: [],
                // 控制添加对话框的添加与隐藏
                addParamsDialogVisible: false,
                addParamsForm: {
                    attr_name: ''
                },
                addParamsFormRules: {
                    attr_name: [
                        { required: true, message: '请输入属性', trigger: 'blur' }
                        // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ]
                },
                editParamsDialogVisible: false,
                // 修改的表单数据对象
                editParamsForm: {},
                // 修改表单的验证规则
                editParamsFormRules: {
                    attr_name: [
                        { required: true, message: '请输入属性', trigger: 'blur' }
                        // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            // 获取所有的商品分类列表
            this.getCateList()
        },
        methods: {
            async getCateList() {
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status !== 200) {
                    return this.$message({
                        message: res.meta.msg,
                        type: 'error'
                    })
                }
                this.cateList = res.data
            },
            // 选择商品分类发生改变
            selectChanged() {
                this.getParamsData()
            },
            // tab  页签点击事件的处理函数
            handleTabClick() {
                this.getParamsData()
                // console.log('tag', this.activeName)
            },
            // 获取参数的列表数据
            async getParamsData() {
                if (this.selectedCateKeys.length !== 3) {
                    this.selectedCateKeys = []
                    this.$message.warning('仅支持3级菜单')
                    this.manyTableData = []
                    this.onlyTableData = []
                    return
                }
                // console.log(this.selectedCateKeys[2])

                // 根据所选分类id 和当前所处的面板 获取对应的参数
                const { data: res } = await this.$http.get(
                        `categories/${this.cateId}/attributes`,
                        {
                            params: { sel: this.activeName }
                        }
                )
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                // console.log('获取面板', res.data)
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                    // 文本框的显示与隐藏
                    item.inputVisible = false
                    // 文本框的输入内容
                    item.inputValue = ''
                })
                console.log(res.data)
                if (this.activeName === 'many') {
                    this.manyTableData = res.data
                } else {
                    this.onlyTableData = res.data
                }
            },
            // 监听添加对话框的关闭事件
            addDialogClosed() {
                this.$refs.addParamsFormRef.resetFields()
            },
            // 点击按钮添加参数
            addParams() {
                this.$refs.addParamsFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post(
                            `categories/${this.cateId}/attributes`,
                            {
                                attr_name: this.addParamsForm.attr_name,
                                attr_sel: this.activeName
                            }
                    )
                    if (res.meta.status !== 201) {
                        return this.$message.warning(res.meta.msg)
                    } else {
                        this.$message.success(res.meta.msg)
                        if (this.activeName === 'many') {
                            this.manyTableData.push(res.data)
                        } else {
                            this.onlyTableData.push(res.data)
                        }
                        this.addParamsDialogVisible = false
                    }
                    // console.log('tag', res)
                })
            },
            // 点击按钮展示修改对话框
            async showEditDialog(id) {
                // this.editParamsForm = scope.row
                this.editParamsDialogVisible = true
                const { data: res } = await this.$http.get(
                        `categories/${this.cateId}/attributes/${id}`,
                        {
                            params: { attr_sel: this.activeName }
                        }
                )
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.editParamsForm = res.data
                // console.log('tag', res)
            },
            // 重置修改的表单
            editDialogClosed() {
                this.$refs.editParamsFormRef.resetFields()
                this.editParamsDialogVisible = false
                this.getParamsData()
            },
            // 保存修改的参数
            editParams: function() {
                this.$refs.editParamsFormRef.validate(async valid => {
                    if (!valid) {
                        return
                    }
                    const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
                        attr_name: this.editParamsForm.attr_name,
                        attr_sel: this.activeName
                    })
                    if (res.meta.status !== 200) {
                        return this.$message.error(res.meta.msg)
                    }
                    this.$message.success(res.meta.msg)
                    this.editParamsDialogVisible = false
                    this.getParamsData()
                })
                // console.log('tag', '保存')
            },
            // 删除参数
            deleteParams: function(attr_id) {
                this.$confirm(`此操作将永久删除该${this.titleText}, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteParamsById(attr_id)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            // 提交删除到服务器
            async deleteParamsById(attr_id) {
                const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
                if (res.meta.status !== 200) return this.$message.warning(res.meta.msg)
                this.$message.success(res.meta.msg)
                this.getParamsData()
            },
            // 点击按钮显示输入文本框
            showInput(row) {
                row.inputVisible = true
                // 让文本框自动获得焦点
                this.$nextTick(_ => {
                    //$nextTick 方法的作用是，当页面上的元素被重新渲染之后，才会指定回调函数中的代码
                    console.log(_)
                    this.$refs.saveTagInput.$refs.input.focus()
                })
            },
            // 文本框失去焦点或者按下了Enter键
            handleInputConfirm: function(row) {
                if (row.inputValue.trim().length === 0) {
                    row.inputVisible = false
                    row.inputValue = ''
                    return
                }
                // 如果没有return 说明用户输入了内容,做后续处理
                row.attr_vals.push(row.inputValue.trim())
                // 需要发起请求保存这次操作
                this.saveAttrVals(row)
                row.inputVisible = false
                row.inputValue = ''
            },
            // 删除对应的参数选项
            HandleClose(i, row) {
                console.log(row)
                row.attr_vals.splice(i, 1)
                this.saveAttrVals(row)
                console.log(row.attr_vals.splice(i, 1))
            },
            async saveAttrVals(row) {
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                })
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                } else {
                    this.$message.success(res.meta.msg)
                }
            }
        },
        computed: {
            // 如果按钮被禁用，则返回true 否则返回false
            isBtnDisabled() {
                return this.selectedCateKeys.length !== 3
            },
            // 当前选中的三级分类id
            cateId() {
                if (this.selectedCateKeys.length !== 3) {
                    return null
                } else {
                    return this.selectedCateKeys[2]
                }
            },
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数'
                } else {
                    return '静态属性'
                }
            }
        }
    }
</script>

<style lang = "less" scoped>
    .el-row {
        padding: 10px;
    }

    .el-table {
        margin-top: 15px;
    }

    .el-tag {
        margin: 5px;
    }

    .el-tag + .el-tag {
        margin-left: 10px;
    }

    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
